package com.huarui.store.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.xwork.StringUtils;
import org.ewaf.framework.action.BaseAction;
import org.ewaf.framework.model.ListModel;
import org.ewaf.framework.util.HttpUtil;
import com.huarui.store.model.Store;
import com.huarui.store.service.StoreService;
import com.huarui.user.model.SessionMessage;
import com.huarui.user.security.UserHolder;
import com.huarui.util.PinyinToolkit;

@SuppressWarnings("serial")
public class StoreAction extends BaseAction {

	private String dir;
	private String sort;
	private int start;
	private int limit;
	private StoreService storeService;
	private SessionMessage sessionMessage;
	private Map<String,Object> resultMap=new HashMap<String, Object>();
	public String index() {

		sessionMessage = UserHolder.getCurrentSessionMessage();

		return "index";
	}

	@SuppressWarnings("unchecked")
	public String query() throws IOException {

		sessionMessage = UserHolder.getCurrentSessionMessage();

		StoreListModel lm = getModelUtil(httpServletRequest);

		Integer companyId = sessionMessage.getCompanyId();
		
		ListModel<Store> listModel =null;

	try{	
		
		 listModel = storeService.getStoresByConditions(lm, companyId);

	    }catch (Exception e) {

	    	resultMap.put("failure", "服务器正则升级中...");
	    	
	    	return "json";
	}
	
		
		JSONArray root = JSONArray.fromObject(listModel.getResult());

		// 分页信息
		resultMap.put("totalProperty", listModel.getTotal());
		resultMap.put("page", lm.getPage());
		resultMap.put("root", root);
		
		return "json";
	}

	@SuppressWarnings("unchecked")
	public String findStoreCombo() {
		sessionMessage = UserHolder.getCurrentSessionMessage();
		@SuppressWarnings("unused")
		JSONObject jsonObject = new JSONObject();
		Map m = new HashMap();
		// m.put("userId", sessionMessage.getUserId());
		m.put("companyId", sessionMessage.getCompanyId());
		m.put("isDelete",0);
		List<Map> list = storeService.findByComIdAndDepId(m);
		JSONArray root = new JSONArray();
		for (Map map : list) {
			JSONObject object = new JSONObject();
			object.put("varIndex", map.get("id"));
			object.put("varName", map.get("name"));
			root.add(object);

		}
		resultMap.put("root", root);
		
		return "json";
		
	}

	@SuppressWarnings("unchecked")
	public String save() throws IOException {
		sessionMessage = UserHolder.getCurrentSessionMessage();
		Integer companyId = sessionMessage.getCompanyId();
		HttpServletRequest request = HttpUtil.getRequest();
		String jsonAll = request.getParameter("jsonAll");
		JSONObject jsonObject = JSONObject.fromObject(jsonAll);
		Store store = (Store) JSONObject.toBean(jsonObject, Store.class);
		
		if (store.getId()!= null) {

			Map map = new HashMap();
			map.put("name", store.getName());
			map.put("companyId",companyId);
			map.put("departmentId",store.getDepartmentId());
			Store so = storeService.getByName(map);

			if(so!=null){	
				if(!store.getId().equals(so.getId())){			
	     	    resultMap.put("failure", "仓库名称不能重复");
	     	    return "json";
						
			}
		  }
		try{
				
			store.setPyCode(PinyinToolkit.cn2FirstSpell(store.getName()));
			Store st=(Store)storeService.getById(store.getId());
			st.setCompanyId(companyId);
			st.setDepartmentId(store.getDepartmentId());
			st.setDepartmentName(store.getDepartmentName());
			st.setName(store.getName());
			st.setPyCode(PinyinToolkit.cn2FirstSpell(st
					.getName()));
			storeService.update(st);

               }catch (Exception e) {
				
            	   resultMap.put("failure", "更新失败");
				
            	   return "json";
			}
		} else {
		
			Map map = new HashMap();
			map.put("name", store.getName());
			map.put("companyId",companyId);
			map.put("departmentId",store.getDepartmentId());
			Store so = storeService.getByName(map);
			if(so!=null){
				
	     	    resultMap.put("failure", "仓库名称不能重复");
	     	    return "json";
						
			}
			
		try{
			Map m = new HashMap();
			m.put("name", store.getName());
			m.put("companyId",companyId);
			m.put("isDelete", true);
			m.put("departmentId",store.getDepartmentId());
			Store st= storeService.getByName(m);
			if(st!=null){
				
				st.setIsDelete(0);
				storeService.update(st);
			}else{
			
			store.setCompanyId(companyId);
			store.setPyCode(PinyinToolkit.cn2FirstSpell(store.getName()));
			storeService.create(store);
			
			}
		  }catch (Exception e) {
			e.printStackTrace();
			  resultMap.put("failure", "保存失败");
			  
			  return "json";
			
		}
		}
		resultMap.put("success", "OK");
		resultMap.put("store", store);
		return "json";
	}

	public String delete() throws IOException {

		HttpServletRequest request = HttpUtil.getRequest();

		String id = request.getParameter("id");

		if (StringUtils.isNotBlank(id)) {

			Integer storeId = Integer.valueOf(id);

			try {

				Store store = (Store) storeService.getById(storeId);

				store.setIsDelete(1);

				storeService.update(store);

			} catch (Exception e) {
				
			   resultMap.put("failure", "删除失败");
					
          	   return "json";
			}

		} else {

		   resultMap.put("failure", "该对象不存在");
			
       	   return "json";
		}

		return null;
	}
	public String revertStore() throws IOException {

		HttpServletRequest request = HttpUtil.getRequest();

		String id = request.getParameter("id");

		if (StringUtils.isNotBlank(id)) {

			Integer storeId = Integer.valueOf(id);

			try {

				Store store = (Store) storeService.getById(storeId);
				store.setIsDelete(0);

				storeService.update(store);

			} catch (Exception e) {
				e.printStackTrace();
			   resultMap.put("failure", "更新失败");
					
          	   return "json";
			}

		} else {

		   resultMap.put("failure", "该对象不存在");
			
       	   return "json";
		}

		return null;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getSort() {
		return sort;
	}

	public void setSort(String sort) {
		this.sort = sort;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public void setStoreService(StoreService storeService) {
		this.storeService = storeService;
	}

	public SessionMessage getSessionMessage() {
		return sessionMessage;
	}

	public void setSessionMessage(SessionMessage sessionMessage) {
		this.sessionMessage = sessionMessage;
	}

	public Map<String, Object> getResultMap() {
		return resultMap;
	}
	
	private StoreListModel getModelUtil(HttpServletRequest request) {
		
		StoreListModel storeListModel=new StoreListModel();
		storeListModel.setPageSize(limit);
		storeListModel.setStart(start);
		
		if(StringUtils.isNotBlank(sort)){
		
		    storeListModel.setOrderBy(sort);
		
		}else{
			
			storeListModel.setOrderBy("id");
		}
		if(StringUtils.isNotBlank(dir)){
		
		   storeListModel.setDesc(dir.equalsIgnoreCase("desc") ? true : false);
		
		}else{
			
			storeListModel.setDesc(false);
		}
		String jsonAll = request.getParameter("jsonAll");
		
		if (StringUtils.isNotBlank(jsonAll)) {

			JSONObject jsonObject = JSONObject.fromObject(jsonAll);
			
			storeListModel.setIsDelete(jsonObject.getString("isDelete"));
			
		}
				
		return storeListModel;
	}

}
